package com.xhwl.centiotdata.integrator;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.integration.IntegrationSystemConfig;
import com.xhwl.common.utils.Md5Util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;

/**
 * Falcon.cao @Copyright (C), 2022, 兴海物联
 * Date: 2022/10/5 9:54
 * Description: 科拓 集成处理器
 */
public class KeytopIntegrationHandler {

    public KeytopIntegrationHandler() {
        logger = LoggerFactory.getLogger(getClass().getName());
    }

    protected Logger logger;

    public String execute(IntegrationSystemConfig config, String command, String target, JSONObject data) {
        JSONObject params = new JSONObject();
        params.put("appCode", config.getApp());
        params.put("cmd", command);
        params.put("data", data);

        long ts = System.currentTimeMillis();
        params.put("sign", onSign(command, String.valueOf(ts), config.getApp(), config.getSk()));
        params.put("ts", ts);

        HttpRequest request = HttpUtil.createPost(config.getHost() + target + command);
        HttpResponse response = request.body(params.toJSONString()).execute();
        if (response == null || response.getStatus() != 200) {
            return null;
        }
        String body = response.body();
        logger.info("【请求科拓 {}】结果：{}", command, body);
        return body;
    }

    /**
     * 解析结果
     */
    public JSONObject parse(String body) {
        if (StringUtils.isNotBlank(body)) {
            JSONObject result = JSON.parseObject(body);
            if (Boolean.TRUE.equals(result.getBoolean("success"))) {
                return result;
            }
        }
        return new JSONObject();
    }

    private static String onSign(String cmd, String ts, String app, String sk) {
        String source = cmd + ts + app + sk;
        return Md5Util.encrypt(source).toLowerCase();
    }

}